package models;

import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
import org.artofsolving.jodconverter.office.OfficeManager;
import org.odftoolkit.odfdom.doc.OdfSpreadsheetDocument;
import org.odftoolkit.odfdom.doc.OdfTextDocument;
import org.odftoolkit.odfdom.doc.table.OdfTable;
import org.odftoolkit.odfdom.doc.table.OdfTableCell;
import org.odftoolkit.odfdom.doc.table.OdfTableColumn;
import org.odftoolkit.odfdom.doc.table.OdfTableRow;
import org.odftoolkit.odfdom.dom.style.OdfStyleFamily;
import org.odftoolkit.odfdom.dom.style.props.OdfParagraphProperties;
import org.odftoolkit.odfdom.dom.style.props.OdfStyleProperty;
import org.odftoolkit.odfdom.dom.style.props.OdfTextProperties;
import org.odftoolkit.odfdom.incubator.doc.office.OdfOfficeAutomaticStyles;
import org.odftoolkit.odfdom.incubator.doc.style.OdfStyle;
import org.odftoolkit.odfdom.pkg.OdfFileDom;
import play.Play;
import play.data.format.Formats;
import play.data.validation.Constraints;
import play.db.ebean.Model;

import javax.persistence.*;
import java.io.File;
import java.util.*;

/**
 * Created by richard on 16/06/14.
 */
@Entity

public class Employe extends Model {
   @Constraints.Required
   public String adresseMail;
    @Constraints.Required
   public String nom;
   @Constraints.Required
   public String prenom;
   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   @Column(name = "id", unique = true, nullable = false)
    public long  id;

    @Formats.DateTime(pattern="dd/MM/yyyy")
    public Date dateNaissance = new Date();

    public static Finder<Long, Employe> find = new Finder<Long, Employe>(
            Long.class, Employe.class
    );
    private String pathEmp;
    private String path;
    private String outputFileName;


    public  String toLog() {
        return this.adresseMail+"|"+this.nom+"|"+this.prenom;

    }

    @OneToMany(mappedBy="employe", cascade=CascadeType.REMOVE)
    @OrderBy("dateDebut")

    public List<Absence> AbsencesList = new ArrayList<Absence>();



    public ArrayList<JourAbsence> getListeJourAbsence(Date Debut,Date Fin){
        ArrayList<JourAbsence> res= new ArrayList<JourAbsence>();
        Iterator I = this.AbsencesList.iterator();
      //  System.out.println(this.AbsencesList.size());
        while (I.hasNext()){
            Absence abs = (Absence) I.next();


            //on devrait tester date de déb date de FIn TODO
            java.util.Calendar c1 = java.util.Calendar.getInstance();
            java.util.Calendar c2 = java.util.Calendar.getInstance();
            c1.setTime(abs.dateDebut);
            c2.setTime(abs.dateFin);



         //   System.out.println(abs.dateDebut + " --" + abs.dateFin);
            //System.out.println(c1.getTime() + " --- " + c2.getTime() );
            while(c1.getTimeInMillis() < c2.getTimeInMillis()) {

               // System.out.println(c1.getTimeInMillis());
                JourAbsence j = new JourAbsence();
                j.annee = c1.get(Calendar.YEAR);
                j.numeroJour = c1.get(Calendar.DAY_OF_YEAR);
                j.jourDansMois =  c1.get(Calendar.DAY_OF_MONTH);
                j.mois =  c1.get(Calendar.MONTH);
                res.add(j);
                c1.add(Calendar.DAY_OF_YEAR, 1);
            }


        }

        return res;


    }


//Generate Good planning

    private void convertODttopdf(){
           /* OfficeManager officeManager = new DefaultOfficeManagerConfiguration()
                    .setOfficeHome("/Volumes/Server HD/Applications/OpenOffice.org.app/Contents/")
                    .setConnectionProtocol(OfficeConnectionProtocol.PIPE)
                    .setPipeNames("office1", "office2")
                    .setTaskExecutionTimeout(30000L)
                    .buildOfficeManager();*/
        
        String OpenOfficeHome = Play.application().configuration().getString("planning.oHome");
       // File oHome = new File ("/Volumes/Server HD/Applications/OpenOffice.org.app/Contents/");
        File oHome = new File(OpenOfficeHome);
        OfficeManager officeManager = new DefaultOfficeManagerConfiguration().setOfficeHome(oHome).buildOfficeManager();

        officeManager.start();

        OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
        converter.convert(new File(outputFileName), new File(pathEmp+"/"+this.id+"/planning_employe.pdf"));

        officeManager.stop();
    }
    private void updatePlanningODT (){
        String inputFileName;

        OdfSpreadsheetDocument outputDocument = null;

        outputFileName = pathEmp+"/"+this.id+"/planning_employe.ods";


        OdfTable table;
        OdfTableRow row;
        OdfTableColumn column;
        OdfTableCell cell;
        OdfFileDom contentDom;

         OdfOfficeAutomaticStyles contentAutoStyles;


        // Create a text document from a standard template (empty documents within the JAR)
        OdfTextDocument odt = null;
        try {
            //outputDocument = OdfSpreadsheetDocument.newSpreadsheetDocument();

            //ou

            // odsDoc = OdfSpreadsheetDocument.loadDocument(infile);
            path = Play.application().configuration().getString("planning.directory.model");

            File infile = new File((path+"planning.ods"));
            outputDocument = OdfSpreadsheetDocument.loadDocument(infile);
            contentAutoStyles = outputDocument.getContentDom().getOrCreateAutomaticStyles();
            // Append text to the end of the document.
            contentDom = outputDocument.getContentDom();
            table = outputDocument.getTableList().get(0);
            //cell = table.getCellByPosition(0, 0);
            //cell.setStringValue("TEST");

            // J1 nom

            // Janvier Colonne -> 2
            //Fevrier colonne -> 5
            // jour Un -> ligne 4

            cell = table.getCellByPosition(9,0);
            cell.setStringValue(this.nom);
            // Pour le modèle utilisé de calendrier (Cellule en haut à gauche 00 )
            ArrayList<JourAbsence> liste= getListeJourAbsence(null,null);
            Iterator I = liste.iterator();
            while (I.hasNext()){
                    JourAbsence crt = (JourAbsence) I.next();
                    System.out.println("-->"+ crt +  "  " +(((crt.mois+1)*3)-1)+" x:y " +(crt.jourDansMois+3) );
                    cell = table.getCellByPosition(((crt.mois+1)*3)-1,crt.jourDansMois+3);

                   // cell.setStringValue("X");
                    if (crt.type.equals(JourAbsence.TYPEJOUR.vacances)) {
                        //cell.setStringValue("C");
                        //cell.setFormula("C");
                      //  cell.setCellStyleName("CCase");
                     //  contentAutoStyles.newStyle(OdfStyleFamily.TableCell);
                     //  contentAutoStyles.getCurrencyStyle("CCase");
                        OdfStyle style = contentAutoStyles.newStyle(OdfStyleFamily.TableCell);

                        style.setStyleDataStyleNameAttribute("CCase");
                        System.out.println(cell.getValueType());
                       // cell.setDisplayText("X","CCase");

                        style = contentAutoStyles.newStyle(OdfStyleFamily.TableCell);
                        String noaaTempStyleName = style.getStyleNameAttribute();
                        style.setStyleDataStyleNameAttribute("numberTemperatureStyle");
                   //     style.setProperty(org.odftoolkit.odfdom.doc.table.OdfTableCell. OdfStyleParagraphProperties.TextAlign, "right");

                        cell.setStringValue("C");
                            System.out.println(cell.getStyleName());



                    }
                    cell.setHorizontalAlignment("center");





                }




            //create table object


// Save document
            outputDocument.save(outputFileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void updatePlanning() {

        pathEmp = Play.application().configuration().getString("planning.directory.employe");

        //test si directory de l'mployé existe
        File fb = new File(pathEmp+"/"+this.id);
        if (!fb.exists()){
            fb.mkdir();
        }
        // Maintenant je récupére les intervalles d'absence et je crée la liste des jours d'absence de l'meployé
        //ArrayList<JourAbsence> liste= getListeJourAbsence(null,null);
        //Iterator I = liste.iterator();
        // on parcours la liste des jours d'absence et on met à jour les formats persistant
        // Format Json
        // Format openoffice puis le pdf

       // while (I.hasNext()){
        //    JourAbsence crt = (JourAbsence) I.next();
            //System.out.println("-->"+ crt);
        //}

        updatePlanningODT();
        convertODttopdf();

    }
}
